const oss_domain = getApp().globalData.oss_domain


  // 数组随机
  const randomSort=(arr)=>{
    var result = [];
    while (arr.length > 0) {
      var randomIndex = Math.floor(Math.random() * arr.length);
      result.push(arr[randomIndex]);
      arr.splice(randomIndex, 1);
    }
    return result;
  }

// 获取本地题库- 节
const get_local_tis=(sec_id)=>{
    let the_key = 'local_tis' + sec_id
    var local_tiku = wx.getStorageSync(the_key) || []
    for(var i=0; i<local_tiku.length; i++){
      let arr = [
        {no:'A', opt:local_tiku[i].a},
        {no:'B', opt:local_tiku[i].b},
        {no:'C', opt:local_tiku[i].c},
      ]
      local_tiku[i].opt_list = randomSort(arr)
    }
    return local_tiku
  }

const get_ti_list=(that,ti_id_list)=>{
    var ti_list = []
    var local_tiku = []
    var section_list = that.data.section_list
    for(var j=0; j<section_list.length;j++){
      let tis = wx.getStorageSync('local_tis' + section_list[j].id)
      if(tis.length>0){
        local_tiku = local_tiku.concat(tis)
      }
    }

    for(var i=0; i<ti_id_list.length; i++){
      for(var k=0; k<local_tiku.length; k++){
        if(ti_id_list[i] == local_tiku[k].ti_id){
          ti_list.push(local_tiku[k])
          break
        }
      }
    }

    for(var i=0; i<ti_list.length; i++){
      let arr = [
        {no:'A', opt:ti_list[i].a},
        {no:'B', opt:ti_list[i].b},
        {no:'C', opt:ti_list[i].c},
      ]
      ti_list[i].opt_list = randomSort(arr)
    }

    return ti_list
  }

// 调整习题列表（乱序习题、乱序选项）
const adjust_tiList=(ti_list)=>{
  // 将习题列表乱序
  ti_list.sort(()=>Math.random()-0.5)
  // 将习题选项乱序
  ti_list = getApp().random_optList_of_tiku(ti_list)
  return ti_list
}

const util = require('../../../utils/util.js')
const domainName = getApp().globalData.domainName
const parameter = getApp().globalData.parameter

const jg_stu_id = wx.getStorageSync('jg_stu_id')

// pages/exercise_book/exercise_book.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    icon_url:oss_domain + 'static/picture/app_icon/',
    domainName,
    section_list:[]
  },

  // 加载收藏习题库
  load_bookmark_tiID_list(){
    if(this.data.mark_count > 0){
      wx.showLoading()
      wx.request({
        url: domainName + '/load_bookmark_tiID_list',
        data: {
          jg_stu_id:jg_stu_id,
          chap_id:this.data.chap_info.chap_id,
        },...parameter,
        success: res => {
          wx.hideLoading()
          // console.log('res.data',res.data)
          let ti_id_list = res.data.ti_id_list
          // 从本地获取习题列表
          var ti_list = get_ti_list(this,ti_id_list)
          // 调整习题列表（乱序习题、乱序选项）
          ti_list = adjust_tiList(ti_list)
          let url_data = 
          '&disable=' + this.data.chap_info.disable + 
          '&tis=' + encodeURIComponent(JSON.stringify(ti_list || []))
          wx.navigateTo({
            url: '/pages/doTi/do_ti/do_ti?' + url_data,
          })
        },
      })
    }

  },
  // 加载错题ID
  load_wrong_list(){

    if(this.data.wrong_count > 0){
      wx.showLoading()
      wx.request({
        url: domainName + '/exercise_book_load_wrongs',
        data: {
          jg_stu_id:jg_stu_id,
          chap_id:this.data.chap_info.chap_id,
        },...parameter,
        success: res => {
          wx.hideLoading()
          let ti_list = res.data.ti_list
          let url_data = 
          '&disable=' + this.data.chap_info.disable + 
          '&tis=' + encodeURIComponent(JSON.stringify(ti_list || []))
          wx.navigateTo({
            url: '/pages/doTi/do_ti/do_ti?' + url_data,
          })
        },
      })
    }

  },
  // 检查习题是否更新
  check_tiku_update(sec_id){
    wx.showLoading({
      title: '检查中...',
    })
    let the_key = 'sec_update' + sec_id
    let sec_last_update_time = wx.getStorageSync(the_key)
    wx.request({
      url: domainName + 'if_need_update_tiku_of_exercise_book',
      data: {
        sec_id:sec_id,
        sec_last_update_time:JSON.stringify(sec_last_update_time),
      },...parameter,
      success: res => {
        wx.hideLoading()
        console.log('res', res.data)
        let new_ti_list = res.data.new_ti_list
        if(new_ti_list.length>0){
          wx.showModal({
            cancelText:'稍后',
            confirmText:'立即更新',
            content: '发现有新题，是否立即更新？',
            showCancel: true,
            title: '提示',
            success: res => {
              if(res.confirm){

                // 将新题 加入 本地题库
                let local_tis = wx.getStorageSync('local_tis' + sec_id)
                this.local_tis = getApp().update_local_tiku(new_ti_list, local_tis) // 对比新题
                wx.setStorageSync('local_tis' + sec_id, this.local_tis)

                // 更新本地，本章节最近更新习题时间
                wx.setStorageSync(the_key, util.formatTime(new Date()))
                wx.showModal({
                  content: '更新完成！',
                  showCancel: false,
                  title: '提示',
                })
              }
            },
          })
        }else{
          wx.showToast({
            title: '已是最新！',
            duration: 2000,
            icon: 'success',
            mask: false,
          })
        }
      },
    })

  },



  tap_sec(e){
    // 1.获取本地习题列表，如果没有习题，则前往服务器获取
    let index = e.currentTarget.id
    let sec_id = this.data.section_list[index].id
    let ti_count = this.data.section_list[index].ti_count
    let finished_count = this.data.section_list[index].finished_count
    let unfinished_count = ti_count - finished_count
    this.local_tis = get_local_tis(sec_id)  // 首先从本地获取顺序题库
    // 如果没有本地题库，则要求加载题库
    if(!this.local_tis.length){
      wx.showModal({
        cancelText: '取消',
        confirmText: '立即检查',
        content: '请先检查更新题库',
        showCancel: true,
        title: '提示',
        success: res => {
          if(res.confirm){
            this.check_tiku_update(sec_id)
          }
        },
      })
    }else{
      var itemList = ['顺序看题','随机练习','顺序练习']
      if(unfinished_count>0){
        itemList.unshift('未完成（' + unfinished_count + '）题')
      }
      wx.showActionSheet({
        itemList: itemList,
        itemColor: '#00b050',
        success: res => {
          let item = itemList[res.tapIndex]
          if(item=='顺序看题'){
            let url_data = 
            '&sec_id=' + sec_id + 
            '&disable=' + this.data.chap_info.disable + 
            '&tis=' + encodeURIComponent(JSON.stringify(this.local_tis || []))
            wx.navigateTo({
              url: '/pages/doTi/read_tis/read_tis?' + url_data,
            })
          }else if(item=='随机练习'){
            var do_what = 'chap_random'
            this.local_tis = adjust_tiList(this.local_tis)
            let url_data = 
            'do_what=' + do_what + 
            '&sec_id=' + sec_id + 
            '&disable=' + this.data.chap_info.disable + 
            '&tis=' + encodeURIComponent(JSON.stringify(this.local_tis || []))
            wx.navigateTo({
              url: '/pages/doTi/do_ti/do_ti?' + url_data,
            })
          }else if(item=='顺序练习'){
            let url_data = 
            '&sec_id=' + sec_id + 
            '&disable=' + this.data.chap_info.disable + 
            '&tis=' + encodeURIComponent(JSON.stringify(this.local_tis || []))
            wx.navigateTo({
              url: '/pages/doTi/do_ti/do_ti?' + url_data,
            })
          }else if(item.slice(0,3)=='未完成'){
            this.load_unfinished_list(jg_stu_id, sec_id)
          }else{
            return
          }
        },
      })
    }

  },

  // 加载未完成的习题列表
  load_unfinished_list(jg_stu_id, sec_id){
    wx.showLoading()
    wx.request({
      url: domainName + 'exercise_book_load_unfinished_list',
      data: {jg_stu_id, sec_id},...parameter,
      success: res => {
        let ti_list = res.data.ti_list
        let url_data = 
        'disable=' + this.data.chap_info.disable + 
        '&tis=' + encodeURIComponent(JSON.stringify(ti_list || []))
        wx.navigateTo({
          url: '/pages/doTi/do_ti/do_ti?' + url_data,
        })
      },
    })
  },


  page_init(jg_stu_id,chap_id){
    wx.request({
      url: domainName + '/exercise_book_init',
      data: {
        jg_stu_id,
        chap_id,
      },...parameter,
      success: res => {
        // console.log('res',res.data)
        wx.hideLoading()
        this.setData({
          section_list:res.data.list,
          mark_count:res.data.mark_count,
          wrong_count:res.data.wrong_count,
        })
      },
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let chap_info = JSON.parse(decodeURIComponent(options.chap_info))
    this.setData({
      chap_info:chap_info
    })
    wx.showLoading()
    this.page_init(jg_stu_id,chap_info.chap_id)
  },

  onHide(){
    this.can_show = true
  },

  onShow(){
    if(this.can_show){
      wx.showLoading()
      this.page_init(jg_stu_id,this.data.chap_info.chap_id)
      this.can_show = false
    }
  },
})

